'use strict';

const db = uniCloud.database();
const collection = db.collection('family');
const collection2 = db.collection('users');
exports.main = async (event, context) => {
	const {
		familyId,
		userName,
		userId,
		oldFamilyId
	} = event;
	// 通过id找到新家庭
	const family = await collection.where({ familyId }).get();
	// 如果找不到新家庭，则返回错误
	if (!family.data) {
		return {
			code: 404,
			msg: '找不到新家庭'
		};
	};

	// 从此家庭的members中加入当前用户，然后更新数据
	let members = family.data[0].members;
	members.push(userName);
	const res = await collection.where({ familyId }).update({ members });

	// 删除此用户之前的家庭表
	const res1 = await collection.where({ familyId: oldFamilyId }).remove();

	// 修改用户在用户表的familyId
	const res2 = await collection2.doc(userId).update({ familyId: familyId });

	//返回数据给客户端
	return {
		code: 0,
		msg: '加入成功',
		// 返回username和新的familyId
		data: {
			username: userName,
			familyId: familyId
		}
	};
};